package com.qiall.boot.util.controller.util;

import org.apache.commons.collections4.CollectionUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BuildSqlUtil {
    public static String buildSql(Map<String, String> param, String sql) {
        for (Map.Entry<String, String> entity : param.entrySet()) {
            String value=entity.getValue();
            if(entity.getKey().contains("_value")){
                value="\'"+value+"\'";
            }
            sql = sql.replaceAll ( entity.getKey(),value);
        }
        return sql;
    }

    public static Map<String, Object> queryForOne(String sql, Statement statement) throws SQLException {

         List<Map<String, Object>> resp= queryForList(sql, statement);
         if(CollectionUtils.isEmpty(resp)){
             return new HashMap<>();
         }
         return resp.get(0);
    }

    public static List<Map<String, Object>> queryForList(String sql, Statement statement) throws SQLException {
        ResultSet resultSet = statement.executeQuery(sql);
        List<Map<String, Object>> stringObjectMapList = new ArrayList<>();
        while (resultSet.next()) {
            Map<String, Object> stringObjectMap = new HashMap<>();
            int columnCount = resultSet.getMetaData().getColumnCount();
            for (int i = 0; i < columnCount; i++) { //循环列
                String columnName = resultSet.getMetaData().getColumnName(i+1); //通过序号获取列名,起始值为1
                String columnValue = resultSet.getString(columnName);  //通过列名获取值.如果列值为空,columnValue为null,不是字符型
                stringObjectMap.put(columnName,columnValue);
            }

            stringObjectMapList.add(stringObjectMap);
        }

        return stringObjectMapList;
    }

}
